package com.xl.generator.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xl.generator.common.ActionResult;
import com.xl.generator.common.ActionResultService;
import com.xl.generator.domain.ChoiceQuestion;
import com.xl.generator.domain.CommonUser;
import com.xl.generator.domain.CompetitionRecord;
import com.xl.generator.domain.CompetitionScheme;
import com.xl.generator.dto.ChoiceQuestionDto;
import com.xl.generator.dto.CompetitionRecordDto;
import com.xl.generator.mapper.ChoiceQuestionMapper;
import com.xl.generator.mapper.CompetitionRecordMapper;
import com.xl.generator.pojo.PageList;
import com.xl.generator.service.CommonUserService;
import com.xl.generator.service.CompetitionRecordService;
import com.xl.generator.service.CompetitionSchemeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 〈〉<br>
 *
 * @author lvln5
 * @Description
 * @date 2022/11/12 19:39
 */
@Api(value = "比赛记录的增删改查")
@RestController
@RequestMapping("competitionRecord")
public class CompetitionRecordController {
	@Resource
	private CompetitionRecordService CompetitionRecordService;
	@Resource
	private CompetitionRecordMapper competitionRecordMapper;

	@Resource
	private ChoiceQuestionMapper choiceQuestionMapper;

	@Resource
	private CompetitionSchemeService competitionSchemeService;

	@Resource
	private CommonUserService commonUserService;
	@ApiOperation(value = "分页查询所有比赛记录", notes="")
	@PostMapping ("list")
	public ActionResult test(@RequestParam("current") Integer current,@RequestParam("Size") Integer size){
		IPage<CompetitionRecord> choiceQuestion = new Page<>();
		choiceQuestion.setCurrent(current);
		choiceQuestion.setSize(size);
		IPage<CompetitionRecord> page = CompetitionRecordService.page(choiceQuestion);
		PageList pageList = new PageList();
		pageList.setTotal(choiceQuestion.getTotal());
		pageList.setData(page);
		return ActionResultService.callBackResultOK(pageList);
	}
	@ApiOperation(value = "分页查询所有比赛记录带用户插件版", notes="分页查询所有比赛记录带用户插件版")
	@PostMapping ("listBeiYong1")
	public ActionResult be1i(@RequestBody CompetitionRecord competitionRecord,@RequestParam("current") Integer current,@RequestParam("Size") Integer size){
		IPage<CompetitionRecordDto> iPage = competitionRecordMapper.selectJoinPage(
				new Page<CompetitionRecord>(current, size),
				CompetitionRecordDto.class,
				new MPJLambdaWrapper<CompetitionRecord>()
						.eq(CompetitionRecord::getUserAccount,competitionRecord.getUserAccount())
						.selectAll(CompetitionRecord.class)
						.selectAs(CommonUser::getUserName, CompetitionRecordDto::getUserName)
						.leftJoin(CommonUser.class, CommonUser::getUserAccount, CompetitionRecord::getUserAccount)
						.selectAs(CompetitionScheme::getCompetitionId,CompetitionRecordDto::getCompetitionId)
						.leftJoin(CompetitionScheme.class,CompetitionScheme::getId,CompetitionRecord::getCompetitionSchemeId)
						.orderByDesc(CompetitionRecord::getJionTime)
		);

		return ActionResultService.callBackResultOK(iPage);
	}
	@ApiOperation(value = "分页查询所有比赛记录带用户插件版", notes="分页查询所有比赛记录带用户插件版")
	@PostMapping ("listBeiYong")
	public ActionResult bei(@RequestParam("current") Integer current,@RequestParam("Size") Integer size){
		IPage<CompetitionRecordDto> iPage = competitionRecordMapper.selectJoinPage(
				new Page<CompetitionRecord>(current, size),
				CompetitionRecordDto.class,
				new MPJLambdaWrapper<CompetitionRecord>()
						.selectAll(CompetitionRecord.class)
						.selectAs(CommonUser::getUserName, CompetitionRecordDto::getUserName)
						.leftJoin(CommonUser.class, CommonUser::getUserAccount, CompetitionRecord::getUserAccount)
						.selectAs(CompetitionScheme::getCompetitionId,CompetitionRecordDto::getCompetitionId)
						.leftJoin(CompetitionScheme.class,CompetitionScheme::getId,CompetitionRecord::getCompetitionSchemeId)
						.orderByAsc(CompetitionRecord::getJionTime)
		);
		return ActionResultService.callBackResultOK(iPage);
	}
	@ApiOperation(value = "获取选择题比赛答题记录", notes="获取选择题比赛答题记录")
	@PostMapping ("getOne")
	public ActionResult getOne(@RequestBody CompetitionRecord competitionRecord){
		CompetitionRecord competitionRecord1 = competitionRecordMapper.selectById(competitionRecord.getId());
		if (competitionRecord1.getCompetitionContent()==null){
			return ActionResultService.callBackResultFail("该比赛无记录。");
		}
		JSONArray jsonArray = JSONArray.parseArray(competitionRecord1.getCompetitionContent());
		List<ChoiceQuestionDto> choiceQuestionDtos = jsonArray.toJavaList(ChoiceQuestionDto.class);
		List<Integer> idList = choiceQuestionDtos.stream()
				.map(ChoiceQuestion::getId).collect(Collectors.toList());
		QueryWrapper<ChoiceQuestion> qw = new QueryWrapper<>();
		qw.lambda().in(ChoiceQuestion::getId,idList);
		List<ChoiceQuestion> choiceQuestionList = choiceQuestionMapper.selectList(qw);
		List<ChoiceQuestionDto> choiceQuestionDtos1 = new ArrayList<>();
		choiceQuestionDtos1 = JSONArray.parseArray(JSON.toJSONString(choiceQuestionList)).toJavaList(ChoiceQuestionDto.class);
		List<ChoiceQuestionDto> choiceQuestionDtos2 = choiceQuestionDtos1.stream().map(c ->
		{
			choiceQuestionDtos.stream()
					.filter(cds-> Objects.equals(cds.getId(),c.getId()))
					.forEach(cds ->{ c.setChoice(cds.getChoice()); });

			return c;
		}).collect(Collectors.toList());
		AtomicInteger flag= new AtomicInteger(1);
		choiceQuestionDtos2.stream().forEach(
				d-> {d.setIsTrue(d.getChoice()!=null&&d.getChoice().equals(d.getAnswer())?"正确":"不正确");
				d.setId(flag.getAndIncrement());
				});
		return ActionResultService.callBackResultOK(choiceQuestionDtos2);
	}


	@ApiOperation(value = "根据个人userAccount分页查询所有比赛记录", notes="")
	@PostMapping ("listByUserAccount")
	public ActionResult test(@RequestParam("current") Integer current,@RequestParam("Size") Integer size,
			@RequestBody CompetitionRecord choice){
		IPage<CompetitionRecord> choiceQuestion = new Page<>();
		choiceQuestion.setCurrent(current);
		choiceQuestion.setSize(size);
		LambdaQueryWrapper<CompetitionRecord> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(CompetitionRecord::getUserAccount,choice.getUserAccount());
		IPage<CompetitionRecord> page = CompetitionRecordService.page(choiceQuestion,queryWrapper);
		PageList pageList = new PageList();
		pageList.setTotal(choiceQuestion.getTotal());
		pageList.setData(page);
		return ActionResultService.callBackResultOK(pageList);
	}
	/**
	 * @param choiceQuestion
	 * @return {@code ActionResult }
	 */
	@ApiOperation(value = "添加比赛记录", notes="注册成功状态码为o,否侧为-1失败")
	@PostMapping("add")
	public ActionResult register(@RequestBody CompetitionRecord choiceQuestion){
		choiceQuestion.setCompetitionContent(choiceQuestion.getCompetitionContentObject().toJSONString());
		boolean save = CompetitionRecordService.save(choiceQuestion);
		QueryWrapper<CommonUser> qw = new QueryWrapper<>();
		qw.lambda().eq(CommonUser::getUserAccount,choiceQuestion.getUserAccount());
		CommonUser commonUser = commonUserService.getOne(qw);
		int credit = commonUser.getTotalCredit();
		if (choiceQuestion.getPass()==1){
			credit += choiceQuestion.getCompetitionScore();
		}
		commonUser.setTotalCredit(credit);


		CompetitionScheme competitionScheme = competitionSchemeService.getById(choiceQuestion.getCompetitionSchemeId());
		if (choiceQuestion.getPass()==1&&commonUser.getDegree()<=competitionScheme.getCompetitionId())
		{
			commonUser.setDegree(competitionScheme.getCompetitionId()+1);
		}
		commonUserService.updateById(commonUser);
		if (save){
			return ActionResultService.callBackResultOK("添加成功");
		}
		return ActionResultService.callBackResultOK("添加失败");
	}
	/**
	 * @param
	 * @return {@code ActionResult }
	 */
	@ApiOperation(value = "删除比赛记录", notes="删除成功状态码为o,否侧为-1失败")
	@PostMapping("del")
	public ActionResult del(@RequestBody CompetitionRecord choiceQuestion){
		LambdaQueryWrapper<CompetitionRecord> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(CompetitionRecord::getId,choiceQuestion.getId());
		boolean remove = CompetitionRecordService.remove(queryWrapper);
		if (remove){
			return	ActionResultService.callBackResultOK("删除成功");
		}
		return ActionResultService.callBackResultFail("删除失败");
	}
	@ApiOperation(value = "更新比赛记录", notes="更新成功状态码为o,否侧为-1失败")
	@PostMapping("update")
	public ActionResult updata(@RequestBody CompetitionRecord choiceQuestion){
//		LambdaQueryWrapper<ChoiceQuestion> queryWrapper = new LambdaQueryWrapper<>();
//		queryWrapper.eq(ChoiceQuestion::getId,choiceQuestion.getId());
		boolean update = CompetitionRecordService.updateById(choiceQuestion);
		if (update){
			return	ActionResultService.callBackResultOK("更新成功");
		}
		return ActionResultService.callBackResultFail("更新失败");
	}
}
